﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace Dnsresolver
{
    public class DnsListener
    {
        private Socket _listenerSocket;
        private SocketAsyncEventArgs _receiveEventArgs;
        private DnsResolvor _dnsResolvor;

        public void StartService()
        {
            _dnsResolvor = new DnsResolvor();
            _dnsResolvor.StartService();
            _listenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            var hostEntry = Dns.GetHostEntry(Dns.GetHostName());
            var endPoint = new IPEndPoint(hostEntry.AddressList[0], 53);
            _listenerSocket.Bind(endPoint);
            InitEventArgs();
            _listenerSocket.ReceiveFromAsync(_receiveEventArgs);
        }

        private void InitEventArgs()
        {
            _receiveEventArgs = new SocketAsyncEventArgs
                                    {
                                        RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0)
                                    };
            _receiveEventArgs.SetBuffer(new byte[512], 0, 512);
            _receiveEventArgs.Completed += OnReceive;
        }

        private unsafe void OnReceive(object sender, SocketAsyncEventArgs e)
        {
            fixed (byte* pData = e.Buffer)
            {

            }
        }

        public void ShutDownService()
        {
            _dnsResolvor.ShutDownService();
            _listenerSocket.Shutdown(SocketShutdown.Both);
            _listenerSocket.Close();
        }

        public void ResolveHost(string text, IPEndPoint ipEndPoint)
        {
            _dnsResolvor.ResolveHost(text, ipEndPoint);
        }
    }
}
